//
//  RadioPlayViewController.m
//  BUDING
//
//  Created by 景强 on 16/4/12.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "RadioPlayViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "RadioSecondModel.h"
#import "RadioMuluViewController.h"
#import "PlayMusicTools.h"

//#import <ShareSDK/ShareSDK.h>
@interface RadioPlayViewController ()<AVAudioPlayerDelegate, RadioDelegate, PlayMusicDelegate>

@property(nonatomic ,assign)NSInteger currenCount;

//@property(nonatomic, retain) AVAudioPlayer *player;
@property (nonatomic, retain) UIImageView *imageView;
@property (nonatomic, retain) NSTimer *timer;
@property (nonatomic, retain) UIProgressView *progress;
@property (nonatomic, retain) UISlider *slider;
@property (nonatomic, retain) UILabel *labelName;
@property (nonatomic, retain) UILabel *labelSinger;
@property (nonatomic, retain) UILabel *labelTime;
@property (nonatomic, retain) UIActivityIndicatorView *active;
@property (nonatomic, retain) UILabel *labelHuanchong;

@property (nonatomic, retain) UIButton *btnStop;
@property (nonatomic, retain) UIButton *btnNext;
@property (nonatomic, retain) UIButton *btnLast;
@property (nonatomic, retain) UIButton *btnVoice;
@property (nonatomic, retain) UIButton *btnDownload;
@property (nonatomic, retain) UIButton *btnCollect;

@property (nonatomic, assign) NSInteger a;
@property (nonatomic, assign) NSInteger b;
@property (nonatomic, copy) NSString *sign;
@property (nonatomic, copy) NSString *filename;


@end

@implementation RadioPlayViewController

static AVAudioPlayer *player;

+(id)sharePlayMusic
{
    static RadioPlayViewController *play = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        play = [[RadioPlayViewController alloc] init];
        
    });
    return play;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fenxiang"] style:UIBarButtonItemStylePlain target:self action:@selector(share)];
    //
    [self creatView];
    
    [PlayMusicTools shareMusic].delegate = self;
    self.currenCount = -1;
}

- (void)creatView{
    self.view.backgroundColor = BLACK;
    
    //    self.btnCollect = [UIButton buttonWithType:UIButtonTypeCustom];
    //    self.btnCollect.frame = CGRectMake(320 * W, 480 * H, 25 * W, 25 * W);
    //    [self.btnCollect setImage:[UIImage imageNamed:@"iconfont-shoucang"] forState:UIControlStateNormal];
    //    [self.btnCollect addTarget:self action:@selector(collectBtn) forControlEvents:UIControlEventTouchUpInside];
    //    [self.view addSubview:self.btnCollect];
    
//    self.btnDownload= [UIButton buttonWithType:UIButtonTypeCustom];
//    self.btnDownload.frame = CGRectMake(370 * W, 480 * H, 25 * W, 25 * W);
//    [self.btnDownload setImage:[UIImage imageNamed:@"Button-Download-01"] forState:UIControlStateNormal];
//    [self.btnDownload addTarget:self action:@selector(downloadBtn) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:self.btnDownload];
    
    self.b = 0;
    
    self.labelName = [[UILabel alloc] initWithFrame:CGRectMake(0, 10 * H, WIDTH, 30 * H)];
    self.labelName.font = [UIFont systemFontOfSize:20 * H weight:0.2];
    self.labelName.textColor = [UIColor whiteColor];
    self.labelName.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.labelName];
    
    self.labelSinger = [[UILabel alloc] initWithFrame:CGRectMake(0, 45 * H, WIDTH, 30 * H)];
    self.labelSinger.textColor = [UIColor whiteColor];
    self.labelSinger.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.labelSinger];
    
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(35 *W, 100 * H, 340 * W, 340 * W)];
    self.imageView.image = [UIImage imageNamed:@"占位图_"];
    self.imageView.backgroundColor = [UIColor greenColor];
    self.imageView.layer.cornerRadius = 170 * W;
    self.imageView.layer.masksToBounds = YES;
    [self.view addSubview:self.imageView];
    
    self.labelTime = [[UILabel alloc] initWithFrame:CGRectMake(0, 495 * H, WIDTH, 20)];
    self.labelTime.textColor = [UIColor grayColor];
    self.labelTime.text = @"00:00 / 00:00";
    self.labelTime.backgroundColor  = [UIColor clearColor];
    self.labelTime.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.labelTime];
    
    self.progress = [[UIProgressView alloc] initWithFrame:CGRectMake(20 * W, 520 * H, WIDTH * 9 / 10, 20)];
    self.progress.progressTintColor = [UIColor redColor];
    self.progress.trackTintColor = [UIColor whiteColor];
    [self.view addSubview:self.progress];
    
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(330 * W, 575 * H, 80 * W, 10)];
    self.slider.transform = CGAffineTransformMakeRotation(-M_PI_2);
    [self.slider addTarget:self action:@selector(changeVoice) forControlEvents:UIControlEventValueChanged];
    self.slider.thumbTintColor = [UIColor clearColor];
    self.slider.minimumValue = 0;
    self.slider.maximumValue = 10;
    
    self.btnStop = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btnStop.frame = CGRectMake(170 * W, 580 * H, 60 * W, 60 * W);
    [self.btnStop setImage:[UIImage imageNamed:@"iconfont-icon12"] forState:UIControlStateNormal];
    [self.btnStop addTarget:self action:@selector(stoped) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.btnStop];
    
    self.btnLast = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btnLast.frame = CGRectMake(90 * W, 580 * H, 60 * W, 60 * W);
    [self.btnLast setImage:[UIImage imageNamed:@"iconfont-zhutishangyiqu"] forState:UIControlStateNormal];
    [self.btnLast addTarget:self action:@selector(last) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.btnLast];
    
    self.btnNext = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btnNext.frame = CGRectMake(250 * W, 580 * H, 60 * W, 60 * W);
    [self.btnNext setImage:[UIImage imageNamed:@"iconfont-zhutixiayiqu"] forState:UIControlStateNormal];
    [self.btnNext addTarget:self action:@selector(next) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.btnNext];
    
    self.btnVoice = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btnVoice.frame = CGRectMake(340 * W, 600 * H, 40 * W, 40 * W);
    [self.btnVoice setImage:[UIImage imageNamed:@"iconfont-shengyin"] forState:UIControlStateNormal];
    [self.btnVoice addTarget:self action:@selector(voiced) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.btnVoice];
    
    
}


//视图将要呈现
-(void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self playCurrentMusic];
    [self donghua];
    
}

//当前播放的歌曲
-(void)playCurrentMusic
{
    
    if (self.index == self.currenCount) {
        
        return;
        
    }else
    {
        self.currenCount = self.index;
        
        RadioSecondModel *model = self.array[self.index];
        self.labelName.text = model.songname;
        self.labelSinger.text = model.songer;
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:model.thumbnail_url] placeholderImage:[UIImage imageNamed:@"占位图_"]];
        [[PlayMusicTools shareMusic ] preparePlayMusicWithUrl:model.filename];
        
    }
    
    
}

#pragma mark 代理方法
//代理方法
- (void)playMusicCurrenTime:(NSString *)currenTime totalTime:(NSString *)totalTime Progress:(CGFloat)progress{
    self.labelTime.text = [NSString stringWithFormat:@"%@ / %@", currenTime, totalTime];
    self.progress.progress = progress;
    //     [self.imageView setTransform:CGAffineTransformRotate(self.imageView.transform, M_PI/20)];
    NSNotification *notice = [NSNotification notificationWithName:@"sing" object:nil userInfo:@{@"name": self.labelName.text, @"singer" : self.labelSinger.text}];
    [[NSNotificationCenter defaultCenter] postNotification:notice];
    
}
//代理方法 , 自动播放
-(void)playNextMusic {
    
    
    NSInteger number =self.array.count - 1;
    
    if (self.currenCount == number) {
        
        self.index = 0;
        
    }
    else
    {
        self.index++;
        
    }
    
    [self playCurrentMusic];
    
    
    
}


- (void)changeVoice{
    [PlayMusicTools shareMusic].player.volume = self.slider.value;
}

- (void)stoped{
    
    if ([[PlayMusicTools shareMusic] isPlaying] == YES) {
        [self.imageView.layer removeAllAnimations];
        [self.btnStop setImage:[UIImage imageNamed:@"bofang"] forState:UIControlStateNormal];
        [[PlayMusicTools shareMusic] pause];
        
        
    }else{
        [self donghua];
        [self.btnStop setImage:[UIImage imageNamed:@"iconfont-icon12"] forState:UIControlStateNormal];
        [[PlayMusicTools shareMusic] play];
        
        
    }
    
}

- (void)last{
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        NSInteger number =self.array.count - 1;
        
        
        if (self.currenCount == 0) {
            
            self.index = number;
            
        }
        else
        {
            self.index--;
            
        }
        
        [self playCurrentMusic];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            
        });
        
    });
    
}

- (void)next{
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        NSInteger number =self.array.count - 1;
        
        if (self.currenCount == number) {
            
            self.index = 0;
        }
        else
        {
            self.index++;
        }
        
        [self playCurrentMusic];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            
        });
        
        
    });
}

- (void)voiced{
    if (self.b == 0) {
        [self.view addSubview:self.slider];
        self.b = 1;
    }else{
        [self.slider removeFromSuperview];
        self.b = 0;
    }
}

- (void)donghua{
    
    CAKeyframeAnimation *ani3 = [CAKeyframeAnimation animation];
    ani3.keyPath = @"transform.rotation";
    NSValue *val1 = [NSValue valueWithCGPoint:CGPointMake(5, 5)];
    NSValue *val2 = [NSValue valueWithCGPoint:CGPointMake(10, 10)];
    NSValue *val3 = [NSValue valueWithCGPoint:CGPointMake(15, 15)];
    NSValue *val4 = [NSValue valueWithCGPoint:CGPointMake(20, 20)];
    NSValue *val5 = [NSValue valueWithCGPoint:CGPointMake(25, 25)];
    ani3.values = @[val1, val2, val3, val4, val5];
    ani3.duration = 20;
    ani3.repeatCount = MAXFLOAT;
    [self.imageView.layer addAnimation:ani3 forKey:nil];
}

//- (void)time{
//    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(jingdutiao) userInfo:nil repeats:YES];
//}

//- (void)share{
//
//      UIView *vie = [[UIView alloc] init];
//    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"BXH1C%)(7`NWF[}JB89}H~K" ofType:@"jpg"];
//    id<ISSContent> publishContent = [ShareSDK content:[NSString stringWithFormat:@"分享内容%@", self.filename]
//                                       defaultContent:@"测试一下"
//                                                image:[ShareSDK imageWithPath:imagePath]
//                                                title:@"ShareSDK"
//                                                  url:@"http://www.mob.com"
//                                          description:@"这是一条测试信息"
//                                            mediaType:SSPublishContentMediaTypeNews];
//    //创建弹出菜单容器
//    id<ISSContainer> container = [ShareSDK container];
//    [container setIPadContainerWithView:vie arrowDirect:UIPopoverArrowDirectionUp];
//
//    //弹出分享菜单
//    [ShareSDK showShareActionSheet:container
//                         shareList:nil
//                           content:publishContent
//                     statusBarTips:YES
//                       authOptions:nil
//                      shareOptions:nil
//                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
//
//                                if (state == SSResponseStateSuccess)
//                                {
//                                    NSLog(@"分享成功");
//                                }
//                                else if (state == SSResponseStateFail)
//                                {
//                                    NSLog(@"分享失败,错误码:%ld,错误描述:%@", [error errorCode], [error errorDescription]);
//                                }
//                            }];
//
//  }
//


- (void)sender:(RadioModel *)model{
    
}

- (void)downloadWithUrl:(NSURL *)url{
    
}

- (void)collectBtn{
    
}

- (void)downloadBtn{
    
    RadioSecondModel *model = self.array[self.index];
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:configuration];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:model.filename]];
    
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath,NSURLResponse *response) {
        
        NSURL *downloadURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        return [downloadURL URLByAppendingPathComponent:[response suggestedFilename]];
        
    } completionHandler:^(NSURLResponse *response,NSURL *filePath, NSError *error) {
        //此处已经在主线程了
        //        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:filePath]];
        //        self.imageView.image = image;
        //        NSLog(@"======%@", filePath);
    }];
    
    [downloadTask resume];
}








- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
